package com.aiti.lulian.gxmh.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.aiti.lulian.gxmh.dto.GxmhEnterpriseSearchParamDto;
import com.aiti.lulian.gxmh.dto.GxmhEnterpriseSearchResultDto;
import com.aiti.lulian.gxmh.vo.GxmhEnterpriseSearchResultVo;
import com.aiti.lulian.mapper.gxmh.GxmhEnterpriseMapper;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * description: 工信门户优质企业数据缓存管理
 * auth fcb
 * date 2025-07-17 17:58
 **/
@Service
@Slf4j
public class GxmhYzqyDataCacheManage {

    private static final String YZQY_TOP_100_KEY = "YZQY_TOP_100";

    @Autowired
    private RedisTemplate<String, GxmhEnterpriseSearchResultDto> redisTemplate;
    @Autowired
    private GxmhEnterpriseMapper gxmhEnterpriseMapper;

    /**
     * 缓存数据是否存在
     * @return
     */
    public boolean yzqyCacheDataExist() {
        return Boolean.TRUE.equals(redisTemplate.hasKey(YZQY_TOP_100_KEY));
    }

    /**
     * 缓存数据，并打乱顺序
     * @param dataList
     * @return
     */
    public long putYzqyData(List<GxmhEnterpriseSearchResultDto> dataList) {
        if(CollectionUtil.isEmpty(dataList)) {
            return 0L;
        }
        Collections.shuffle(dataList);
        Long count =  redisTemplate.opsForList().rightPushAll(YZQY_TOP_100_KEY, dataList);
        //redisTemplate.expire(YZQY_TOP_100_KEY, 1, TimeUnit.DAYS);
        return count == null ? 0L : count;
    }

    /**
     * 获取缓存数据
     * @param pageNum
     * @param pageSize
     * @return
     */
    public List<GxmhEnterpriseSearchResultDto> getYzqyData(long pageNum, long pageSize) {
        long start = (pageNum - 1) * pageSize;
        long end = start + pageSize - 1;
        return redisTemplate.opsForList().range(YZQY_TOP_100_KEY, start, end);
    }

    @Scheduled(cron = "0 10 1 ? * *")
    public void setYzqyData() {
        redisTemplate.delete(YZQY_TOP_100_KEY);
        GxmhEnterpriseSearchParamDto queryDto = new GxmhEnterpriseSearchParamDto();
        queryDto.setPageNum(1);
        queryDto.setPageSize(100);
        IPage<GxmhEnterpriseSearchResultDto> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        List<GxmhEnterpriseSearchResultDto> resultDtoList = gxmhEnterpriseMapper.queryEnterpriseInfo(page, queryDto);
        this.putYzqyData(resultDtoList);
    }
}
